import logging
from voice_assistant.plugin_system import Plugin
from voice_assistant.event_system import event_system, Events, EventNames

logger = logging.getLogger("WeatherPlugin")

class WeatherPlugin(Plugin):
    """天气查询插件
    
    提供天气查询功能
    """
    
    name = "weather_plugin"
    description = "提供天气查询功能"
    version = "1.0.0"
    author = "Virgo Tool"
    
    def __init__(self, app=None):
        super().__init__(app)
        self.cities = {
            "北京": {"temp": "25°C", "weather": "晴", "humidity": "40%"},
            "上海": {"temp": "28°C", "weather": "多云", "humidity": "65%"},
            "广州": {"temp": "32°C", "weather": "阵雨", "humidity": "80%"},
            "深圳": {"temp": "30°C", "weather": "晴", "humidity": "75%"}
        }
    
    def initialize(self) -> bool:
        """初始化插件"""
        logger.info("天气插件初始化")
        
        # 订阅命令识别事件
        event_system.subscribe(Events.COMMAND_RECOGNIZED, self.handle_command)
        return True
    
    def shutdown(self) -> None:
        """关闭插件"""
        # 取消订阅事件
        event_system.unsubscribe(Events.COMMAND_RECOGNIZED, self.handle_command)
        logger.info("天气插件已关闭")
    
    def handle_command(self, command_data):
        """处理命令"""
        if not command_data or not isinstance(command_data, dict):
            return
        
        # 检查是否是天气查询命令
        command = command_data.get("command", "").lower()
        params = command_data.get("params", {})
        
        # 简单的命令识别
        if command == EventNames.WEATHER:
            # 查找城市名
            city = None
            for city_name in self.cities.keys():
                if city_name in command:
                    city = city_name
                    break
            
            if city:
                self.query_weather(city)
            else:
                # 默认查询北京天气
                self.query_weather("北京")
    
    def query_weather(self, city):
        """查询天气"""
        if city in self.cities:
            weather_data = self.cities[city]
            message = f"{city}天气: {weather_data['weather']}, 温度{weather_data['temp']}, 湿度{weather_data['humidity']}"
            
            # 发布通知事件
            event_system.publish(Events.UI_NOTIFICATION, {
                "title": "天气查询",
                "message": message,
                "type": "info"
            })
            
            logger.info(f"查询天气: {message}")
        else:
            event_system.publish(Events.UI_NOTIFICATION, {
                "title": "天气查询",
                "message": f"抱歉，没有{city}的天气信息",
                "type": "warning"
            })